package com.maben.vue_support.util;

import cn.hutool.jwt.JWTUtil;
import com.maben.vue_support.constant.CommonConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class TokenUtil {
    /**
     * 从redis中获取当前用户缓存信息
     */
    public static  String getCacheUserJsonMessage()throws Exception {
        final String username = getUsernameFormRequest();
        if (StringUtils.isBlank(username)){
            throw new Exception("token less.");
        }
        final String redisKey = CommonConstant.REDIS_USER_HEAD+username;
        if (!RedisUtil.hasKey(redisKey)){
            throw new Exception("user message loss from cache");
        }
        return (String) RedisUtil.get(redisKey);
    }
    /**
     * 从请求中获取token
     */
    public static String getTokenFromRequest(){
        final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String jwtToken = request.getHeader(CommonConstant.HEADER_TOKEN_KEY);
        if (StringUtils.isBlank(jwtToken)){
            jwtToken = request.getParameter(CommonConstant.HEADER_TOKEN_KEY);
        }
        return jwtToken;
    }
    /**
     * 从请求中获取username
     */
    public static String getUsernameFormRequest(){
        final String token = getTokenFromRequest();
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return (String) JWTUtil.parseToken(token).getPayload().getClaim("username");
    }
    /**
     * 从令牌中获取username
     */
    public static String getUsernameFormToken(String token){
        return (String) JWTUtil.parseToken(token).getPayload().getClaim("username");
    }
}
